<template>
  <div ref="chartContainer" class="chart-container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, nextTick, watch } from 'vue';
import { debounce } from "@/utils"; // 确保你有一个 debounce 函数
import * as echarts from 'echarts';

const props = defineProps({
  chartData: {
    type: Object,
    required: true,
    default: () => ({
      title: '',
      xAxisData: [],
      seriesData: [],
    }),
  },
  chartTitle: {
    type: String,
    default: '曲线', // 修正为 String 类型
  },
});

const chartContainer = ref<HTMLDivElement | null>(null); // 确保类型安全
let chartInstance: echarts.ECharts | null = null; // 确保类型安全

// 函数来初始化或更新图表
const initChart = () => {
  if (!chartContainer.value) return; // 确保 chartContainer 存在
  if (!chartInstance) {
    chartInstance = echarts.init(chartContainer.value);
  }

  const option = {
    title: {
      text: props.chartTitle || 'No Title',
      textStyle: {
        fontSize: 12,
        color: '#fff',
      },
      left: 'center',
      top: '10px',
    },
    tooltip: {
      trigger: 'axis',
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: props.chartData.xAxisData,
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '数据',
        type: 'line',
        smooth: true, // 使线条平滑
        data: props.chartData.seriesData,
        itemStyle: {
          color: '#06cacd', // 线条颜色
        },
      },
    ],
  };

  chartInstance.setOption(option);
};

// 处理图表缩放
const handleChartResize = debounce(() => {
  if (chartInstance) {
    chartInstance.resize();
  }
}, 100);

// 组件挂载时
onMounted(() => {
  nextTick(() => {
    initChart(); // 初始化图表
  });

  window.addEventListener('resize', handleChartResize); // 窗口调整时重新调整图表
});

// 监视数据变化
watch(() => props.chartData, () => {
  initChart(); // 重新初始化图表
}, { deep: true });

// 组件卸载时清理
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleChartResize);
  if (chartInstance) {
    chartInstance.dispose(); // 清理图表实例
    chartInstance = null; // 防止再次调用
  }
});
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style>
